package org.example.sb_api.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.sb_api.annotation.RequireLogin;
import org.example.sb_api.common.Result;
import org.example.sb_api.util.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        
        // 检查是否有RequireLogin注解
        RequireLogin requireLogin = method.getAnnotation(RequireLogin.class);
        if (requireLogin == null) {
            // 再检查类上是否有注解
            requireLogin = method.getDeclaringClass().getAnnotation(RequireLogin.class);
        }
        
        // 没有注解或者不需要登录
        if (requireLogin == null || !requireLogin.required()) {
            return true;
        }

        // 验证token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            handleError(response, 401, "请先登录");
            return false;
        }

        try {
            token = token.substring(7);
            if (JwtUtil.validateToken(token)) {
                // 将用户ID存入request属性中
                request.setAttribute("userId", JwtUtil.getUserIdFromToken(token));
                return true;
            } else {
                handleError(response, 401, "登录已过期，请重新登录");
                return false;
            }
        } catch (Exception e) {
            handleError(response, 401, "无效的token，请重新登录");
            return false;
        }
    }

    private void handleError(HttpServletResponse response, int code, String message) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(code);
        PrintWriter out = response.getWriter();
        out.write(objectMapper.writeValueAsString(Result.error(code, message)));
        out.flush();
        out.close();
    }
} 